﻿using Pay.Dal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pay.Model.Dto;
using Pay.Dapper;
using Dapper;
using Dapper.Contrib;
using Pay.Model.Model;
using Pay.Model.Interfaces;
using Dapper.Contrib.Extensions;
using Pay.Model.Enums;

namespace Pay.DalImplement
{
    public class UserDalImplement : IUserDal
    {
        /// <summary>
        /// 新增商家用户
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<long> AddMerchantUser(MerchantInfo info)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                    return await conn.InsertAsync<MerchantInfo>(info);
               

            }
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<long> Add(UserInfo user)
        {

            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                
              return await conn.InsertAsync<UserInfo>(user);
                

            }

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<bool> Delete(UserInfo user)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                return await conn.DeleteAsync<UserInfo>(user);
            }
        }

        public async Task<List<PermissionDto>> GetAllPermisson(long userId)
        {
            using (var conn = ConnectionFactory.GetReadConnection())
            {
                string sql = "select mu.MenuName, r.RoleName,p.ActionName,p.ControllerName,p.PermissionName from user_role u inner join role_info r on u.RoleId = r.Id inner join  role_menu m on m.RoleId = r.Id inner join menu mu on m.MenuId = mu.Id inner join permission p on p.MenuId = m.MenuId  where u.UserId = @userId";
                var data= await conn.QueryAsync<PermissionDto>(sql, new { userId = userId });
                return data.ToList();
            }
        }

        public async Task<UserInfo> GetUserByName(string UserName)
        {
            
            using (var conn = ConnectionFactory.GetReadConnection())
            {
                string sql = "SELECT [Id],[UserName],[Pwd],[Type],[NikeName],[Email],[Phone],[ImageUrl],[Remark],[IsEnable],[ExpireTime],[CreateTime],[LastTime],[MerchantId]  FROM [Lot_Pay].[dbo].[user_info] where userName=@UserName";

               var model= await conn.QueryFirstOrDefaultAsync<UserInfo>(sql,new{UserName=UserName});

                return model;
            }
        }
        /// <summary>
        /// 获取用户根据用户Id
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<UserInfo> GetUserById(long userId)
        {
            using (var conn = ConnectionFactory.GetReadConnection())
            {
                string sql = "SELECT [Id],[UserName],[Pwd],[Type],[NikeName],[Email],[Phone],[ImageUrl],[Remark],[IsEnable],[ExpireTime],[CreateTime],[LastTime]  FROM [user_info] where id=@id";

                var model = await conn.QueryFirstOrDefaultAsync<UserInfo>(sql, new { id = userId });

                return model;
            }
        }

        public async Task<IPagedOutput<UserOutPut>> GetUserPage(long? mId, UserType? type, string searchWord, DateTime? timeBegin = null, DateTime? timeEnd = null, int offset = 10, int rows = 1)
        {
            StringBuilder sb = new StringBuilder("select u.Id, u.UserName,u.Type,u.CreateTime,r.RoleName,u.IsEnable ,m.FeeRate,u.MerchantId,m.FreezeAmount,m.TotalAmount from user_info u left join user_role uo on u.Id=uo.UserId left join role_info r on uo.RoleId=r.Id left join merchant_info m on m.id=u.MerchantId where 1=1");
            DynamicParameters param= new DynamicParameters();
            if (mId.HasValue)
            {
                sb.Append(" and u.merchantid=@mId");
                param.Add("@mId", mId.Value);
            }

            if (!string.IsNullOrWhiteSpace(searchWord))
            {
                sb.Append(" and u.username like '%'+@searchWord+'%'");
                param.Add("@searchWord", searchWord);
            }
            if(timeBegin.HasValue&&timeEnd.HasValue)
            {
                sb.Append(" and  u.createtime >=@timeBegin and u.createTime <=@timeEnd");
                param.Add("@timeBegin", timeBegin.Value);
                param.Add("@timeEnd", timeEnd.Value);

            }

            if (type.HasValue)
            {
                sb.Append(" and u.type=@type");
                param.Add("@type", (int)type.Value);
            }

            using (var conn = ConnectionFactory.GetReadConnection())
            {
              return await conn.PagedByAsync<UserOutPut>(sb, param, offset, rows, "createTime", false);
            }        
        }


        public async Task<bool> Update(UserInfo user)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                return await conn.UpdateAsync<UserInfo>(user);
            }
        }

        public async Task<bool> UpdateMerchant(MerchantInfo user)
        {
            using (var conn = ConnectionFactory.GetWriteConnection())
            {
                return await conn.UpdateAsync<MerchantInfo>(user);
            }

        }

        public async Task<MerchantInfo> GetMerchantById(long id)
        {
            using (var conn = ConnectionFactory.GetReadConnection())
            {
                string sql = "SELECT [Id],[AppId],[AccessKey],[MerchantCode],[ExpireTime],[CreateTime],[FeeRate]  FROM merchant_info where id=@id";

                var model = await conn.QueryFirstOrDefaultAsync<MerchantInfo>(sql, new { id = id });

                return model;
            }
        }
    }
}
